package com.taotao.portal.web;

import com.taotao.common.TaotaoResult;
import com.taotao.portal.pojo.CartItem;
import com.taotao.portal.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加购物车
     * @param itemId
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/add/{itemId}")
    public String addCart(@PathVariable Long itemId, HttpServletRequest request, HttpServletResponse response, Model model) {
        //添加商品信息
        List<CartItem> cartItemList = cartService.add(itemId, request, response);

        //把购物车中的商品传递给页面
        model.addAttribute("cartList", cartItemList);
        return "cart";
    }

    /**
     * 获取购物车中商品列表
     * @param request
     * @param model
     * @return
     */
    @GetMapping({"/cart","/show"})
    public String toCart(HttpServletRequest request, Model model){
        List<CartItem> cartItemList = cartService.getCartList(request);
        model.addAttribute("cartList",cartItemList);
        return "cart";
    }

    /**
     * 删除购物车中的商品
     * @param itemId
     * @param request
     * @param response
     * @param model
     * @return
     */
    @GetMapping("/delete/{itemId}")
    public String deleteCart(@PathVariable Long itemId, HttpServletRequest request, HttpServletResponse response, Model model){
        List<CartItem> cartItemList = cartService.deleteCart(itemId,request,response);
        model.addAttribute("cartList",cartItemList);
        return "cart";
    }

    /**
     * 修改指定商品的数量
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody
    public TaotaoResult modifyCart(@PathVariable Long itemId,@PathVariable Integer num, HttpServletRequest request, HttpServletResponse response, Model model){
        TaotaoResult taotaoResult = cartService.changeCartItemNum(itemId,num,request,response);
        return TaotaoResult.ok();
    }
}
